package jdk8.stream;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分组后进行排序演示
 */
public class GroupDemo {
    @Test
    public void test1() {
        ArrayList<User> list = new ArrayList();
        list.add(new User("zhangsan", 22));
        list.add(new User("zhangsan", 21));
        list.add(new User("lisi", 10));
        list.add(new User("zhangsan", 20));
        list.add(new User("lisi", 13));
        list.add(new User("wangwu", 12));
        list.add(new User("lisi", 14));
        list.add(new User("wangwu", 19));
        Map<String, List<User>> groupAfterMap = list.parallelStream().collect(Collectors.groupingBy(User::getName));
        print(groupAfterMap);
        Map<String,List<User>> groupAndSortAfterMap = list.stream()
                .sorted(Comparator.comparing(User::getAge))
                .collect(Collectors.groupingBy(User::getName));
        System.out.println("==================================================");
        print(groupAndSortAfterMap);
    }

    public void print(Map<String, List<User>> map ){
        map.forEach((k,v)->{
            v.stream().forEach(f->{
                System.out.println(f);
            });
        });
    }

    public static class User{
        private String name;
        private Integer age;

        public User(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }


}
